//
//  KLMTimePickerTestController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/27.
//

import UIKit

<<<<<<< HEAD
private let DefaultPickerWidth = 33.0 + 18.0
private let DefaultYearExtraWidth = 16.0
private let DefaultUnitWidth = 13.0
private let DefaultYearMinus = 10
private let PickerPadding = 13.0
/// 日期组件数量低于该值，宽度可调大一点
private let CountForAdjustPickerWidth = 3

class CustomDatePickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    
    // MARK: - 嵌套类型
    enum ComponentType: String, CaseIterable {
        case year   = "yyyy"
        case month  = "MM"
        case day    = "dd"
        case hour   = "HH"
        case minute = "mm"
        case second = "ss"
        
        var unitLabel: String {
            switch self {
            case .year:   return "年"
            case .month:  return "月"
            case .day:    return "日"
            case .hour:   return "时"
            case .minute: return "分"
            case .second: return "秒"
            }
        }
    }
    
    // MARK: - 属性
    private var pickerViews = UIView()
    private var components: [ComponentType] = []
    private var pickers: [UIPickerView] = []
    private var labels: [UILabel] = []
    var dateComponents = DateComponents()
    var currentDateComponents = DateComponents()
    
    var dateFormat: String = "yyyy-MM-dd HH:mm" {
        didSet { parseDateFormat() }
    }
    
    var showUnitLabels = false
    var onDateSelected: ((Date, String) -> Void)?
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        currentDateComponents = getCurrentDateComponents()
        setupUI()
        parseDateFormat()
        setupConstraints()
        setupInitialSelections()
    }
    
    // MARK: - UI配置
    private func setupUI() {
        view.backgroundColor = .white
        setupPickerStack()
        setupControlButtons()
    }
    
    private func setupPickerStack() {
        view.addSubview(pickerViews)
        pickerViews.translatesAutoresizingMaskIntoConstraints = false
        pickerViews.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.leading.equalToSuperview()
            if showUnitLabels {
                make.trailing.equalToSuperview().offset(-PickerPadding)
            } else {
                make.trailing.equalToSuperview()
            }
        }
    }
    
    private func setupControlButtons() {
        let buttonView = UIView()
        view.addSubview(buttonView)
        buttonView.translatesAutoresizingMaskIntoConstraints = false
        buttonView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
            make.height.equalTo(50)
            make.top.equalTo(pickerViews.snp.bottom)
        }
        
        let cancelButton = createButton(title: "取消", action: #selector(cancelAction))
        let confirmButton = createButton(title: "确定", action: #selector(confirmAction))
        buttonView.addSubview(cancelButton)
        buttonView.addSubview(confirmButton)
        cancelButton.snp.makeConstraints { make in
            make.leading.bottom.top.equalToSuperview()
            make.trailing.equalTo(confirmButton.snp.leading)
        }
        confirmButton.snp.makeConstraints { make in
            make.trailing.bottom.top.equalToSuperview()
            make.width.equalTo(cancelButton)
        }
        let topLine = UIView()
        let middleLine = UIView()
        topLine.backgroundColor = rgba(242, 242, 242, 1)
        middleLine.backgroundColor = rgba(242, 242, 242, 1)
        buttonView.addSubview(topLine)
        buttonView.addSubview(middleLine)
        topLine.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(0.5)
        }
        middleLine.snp.makeConstraints { make in
            make.height.equalToSuperview()
            make.centerX.equalToSuperview()
            make.width.equalTo(0.5)
        }
    }
    
    // MARK: - 获取当天的日期各个组件
    func getCurrentDateComponents() -> DateComponents {
        return Calendar.current.dateComponents(
            [.year, .month, .day, .hour, .minute, .second],
            from: Date()
        )
    }
    
    // MARK: - 格式化日期字符串解析组件数量
    func parseFormatComponents(_ format: String) -> Set<Calendar.Component> {
        var components: Set<Calendar.Component> = []
        if format.contains("yyyy") { components.insert(.year) }
        if format.contains("MM") { components.insert(.month) }
        if format.contains("dd") { components.insert(.day) }
        if format.contains("HH") || format.contains("hh") { components.insert(.hour) }
        if format.contains("mm") { components.insert(.minute) }
        if format.contains("ss") { components.insert(.second) }
        return components
    }
    // MARK: - 日期处理
    private func parseDateFormat() {
        components.removeAll()
        let pattern = "(yyyy|MM|dd|HH|mm|ss)"
        let regex = try! NSRegularExpression(pattern: pattern)
        let matches = regex.matches(in: dateFormat, range: NSRange(dateFormat.startIndex..., in: dateFormat))
        
        for match in matches {
            guard let range = Range(match.range, in: dateFormat) else { continue }
            let componentStr = String(dateFormat[range])
            if let component = ComponentType(rawValue: componentStr) {
                components.append(component)
            }
        }
        
        
        createPickers()
    }
    //    private func parseDateFormat() {
    //        components.removeAll()
    //        var remainingFormat = dateFormat
    //        if !remainingFormat.isEmpty {
    //            for component in ComponentType.allCases {
    //                if remainingFormat.contains(component.rawValue) {
    //                    components.append(component)
    //                    remainingFormat = remainingFormat.replacingOccurrences(of: component.rawValue, with: "")
    //                }
    //            }
    //        }
    //        createPickers()
    //    }
    
    private func createPickers() {
        pickers.forEach { $0.removeFromSuperview() }
        labels.forEach { $0.removeFromSuperview() }
        pickers.removeAll()
        labels.removeAll()
        
        var layoutX = 0.0
        for (_, component) in components.enumerated() {
            let picker = UIPickerView()
            picker.dataSource = self
            picker.delegate = self
            pickers.append(picker)
            pickerViews.addSubview(picker)
            var width = component == .year ? DefaultPickerWidth + DefaultYearExtraWidth : DefaultPickerWidth
            if components.count < CountForAdjustPickerWidth {
                width = 106
            }
            picker.snp.makeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.width.equalTo(width)
                make.leading.equalTo(layoutX)
            }
            layoutX += width
            
            if showUnitLabels {
                let label = UILabel()
                label.text = component.unitLabel
                label.font = .systemFont(ofSize: 14)
                labels.append(label)
                pickerViews.addSubview(label)
                label.snp.makeConstraints { make in
                    make.leading.equalTo(picker.snp.trailing)
                    make.width.equalTo(DefaultUnitWidth)
                    make.centerY.equalTo(picker)
                }
                layoutX += DefaultUnitWidth
            }
        }
    }
    
    // MARK: - 初始选择设置
    private func setupInitialSelections() {
        for (index, component) in components.enumerated() {
            let picker = pickers[index]
            switch component {
            case .year:
                let startYear = currentDateComponents.year! - DefaultYearMinus
                let endYear = currentDateComponents.year! + DefaultYearMinus
                if let year = dateComponents.year, (startYear...endYear).contains(year) {
                    picker.selectRow(year - startYear, inComponent: 0, animated: false)
                }
            case .month:
                if let month = dateComponents.month, (1...12).contains(month) {
                    picker.selectRow(month - 1, inComponent: 0, animated: false)
                }
            case .day:
                if let day = dateComponents.day, (1...31).contains(day) {
                    picker.selectRow(day - 1, inComponent: 0, animated: false)
                }
            case .hour:
                if let hour = dateComponents.hour, (0...23).contains(hour) {
                    picker.selectRow(hour, inComponent: 0, animated: false)
                }
            case .minute:
                if let minute = dateComponents.minute, (0...59).contains(minute) {
                    picker.selectRow(minute, inComponent: 0, animated: false)
                }
            case .second:
                if let second = dateComponents.second, (0...59).contains(second) {
                    picker.selectRow(second, inComponent: 0, animated: false)
                }
            }
            // 去掉UIPickerView的默认背景色
            picker.subviews.forEach { subView in
                subView.backgroundColor = .clear
            }
        }
    }
    
    // MARK: - 按钮操作
    @objc private func cancelAction() {
        dismiss(animated: true)
    }
    
    @objc private func confirmAction() {
        guard let date = Calendar.current.date(from: dateComponents) else { return }
        let formatter = DateFormatter(format: dateFormat)
        onDateSelected?(date, formatter.string(from: date))
        dismiss(animated: true)
    }
    // MARK: - 计算某年某月的天数
    private func daysInMonth(year: Int, month: Int) -> Int {
        let calendar = Calendar.current
        let date = calendar.date(from: DateComponents(year: year, month: month))!
        return calendar.range(of: .day, in: .month, for: date)?.count ?? 31
    }
    // 更新天数时刷新Picker
    private func updateDayComponent() {
        guard let year = dateComponents.year,
              let month = dateComponents.month,
              let dayIndex = components.firstIndex(of: .day) else { return }
        
        let days = daysInMonth(year: year, month: month)
        let picker = pickers[dayIndex]
        picker.reloadComponent(0)
        
        if let currentDay = dateComponents.day, currentDay > days {
            dateComponents.day = days
            picker.selectRow(days - 1, inComponent: 0, animated: true)
        }
    }
    // MARK: - Picker数据源
    func numberOfComponents(in pickerView: UIPickerView) -> Int { 1 }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        guard let index = pickers.firstIndex(of: pickerView) else { return 0 }
        let type = components[index]
        
        switch type {
        case .year:
            return DefaultYearMinus * 2 // 当前日期前后10年
        case .month:
            return 12
        case .day:
            let year = dateComponents.year ?? currentDateComponents.year!
            let month = dateComponents.month ?? currentDateComponents.month!
            return daysInMonth(year: year, month: month)
        case .hour:
            return 24
        case .minute, .second:
            return 60
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let view = UIView()
        guard let index = pickers.firstIndex(of: pickerView) else { return view }
        
        let label = UILabel()
        label.textAlignment = .center
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        let topLine = UIView()
        let bottomLine = UIView()
        topLine.backgroundColor = rgba(222, 222, 222, 1)
        bottomLine.backgroundColor = rgba(222, 222, 222, 1)
        view.addSubview(topLine)
        view.addSubview(bottomLine)
        topLine.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(0.5)
        }
        bottomLine.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        var title = ""
        switch components[index] {
            case .year: title = String(format: "%04d", currentDateComponents.year! - DefaultYearMinus + row)
            case .month: title = String(format: "%02d", row + 1)
            case .day: title = String(format: "%02d", row + 1)
            case .hour: title = String(format: "%02d", row)
            case .minute, .second: title = String(format: "%02d", row)
        }
        label.font = .systemFont(ofSize: 16.0)
        label.text = title
        
        // 当前滚动选择的一行
        let isCurrentSelectRow = pickerView.selectedRow(inComponent: component) == row
        topLine.isHidden = !isCurrentSelectRow
        bottomLine.isHidden = !isCurrentSelectRow
        
        return view
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 36.0
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        guard let index = pickers.firstIndex(of: pickerView) else { return }
        let type = components[index]
        
        switch type {
        case .year:
            dateComponents.year = currentDateComponents.year! - DefaultYearMinus + row
            updateDayComponent()
        case .month:
            dateComponents.month = row + 1
            updateDayComponent()
        case .day:
            dateComponents.day = row + 1
        case .hour:
            dateComponents.hour = row
        case .minute:
            dateComponents.minute = row
        case .second:
            dateComponents.second = row
        }
        // 强制刷新
        pickerView.reloadComponent(component)
    }
    // MARK: - 计算picker的宽度
    private func calculatePickerWidth() -> CGFloat {
        var width = 0.0
        
        
        return width
    }
    // 调整整体宽度计算
    private func calculateTotalWidth() -> CGFloat {
        let extraPickerWidth = components.contains(where: {$0 == .year}) ? DefaultYearExtraWidth : 0.0
        let labelWidth: CGFloat = showUnitLabels ? DefaultUnitWidth : 0
        let paddingWidth: CGFloat = showUnitLabels ? PickerPadding : 0
        var totalWidth = 0.0
        if components.count >= CountForAdjustPickerWidth {
            totalWidth = CGFloat(components.count) * (DefaultPickerWidth + labelWidth) + extraPickerWidth + paddingWidth
        } else {
            totalWidth = CGFloat(components.count) * (106 + labelWidth) + extraPickerWidth + paddingWidth
        }
        print("预计总长度为：", totalWidth, view.width)
        return totalWidth
    }
    // MARK: - 布局
    private func setupConstraints() {
        preferredContentSize = CGSize(
            width: calculateTotalWidth(),
            height: 240
        )
    }
    
    private func createButton(title: String, action: Selector) -> UIButton {
        let button = UIButton(type: .custom)
        button.setTitle(title, for: .normal)
        button.setTitleColor((title == "确定" ? appMainThemeColor : rgba(38, 38, 38, 1)), for: .normal)
        button.titleLabel?.font = UIFont(safeName: "Alata-Regular", size: 18)
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }
}
// 实现代理方法，禁止自适应全屏样式（关键！！！）
extension CustomDatePickerViewController: UIPopoverPresentationControllerDelegate {
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        // 设置popoverPresentationController?.delegate
        return .none // 强制使用 popover 样式
    }
}
// MARK: - Popover扩展
extension UIViewController {
    func showCustomDatePicker(
        sourceView: UIView,
        dateFormat: String = "yyyy-MM-dd HH:mm",
        showUnits: Bool = false,
        initialDateString: String? = nil,
        completion: @escaping (Date, String) -> Void
    ) {
        let pickerVC = CustomDatePickerViewController()
        pickerVC.dateFormat = dateFormat
        pickerVC.showUnitLabels = showUnits
        // 合并当前日期组件
        var currentComponents = Calendar.current.dateComponents(
            [.year, .month, .day, .hour, .minute, .second],
            from: Date()
        )
        
        if let dateString = initialDateString {
            let formatter = DateFormatter()
            formatter.dateFormat = dateFormat
            formatter.locale = Locale.current
            guard let date = formatter.date(from: dateString) else {
                view.makeToast("错误：日期格式不匹配！", position: .center, title: "提示")
                return
            }
            // 根据格式字符串判断需要覆盖的组件
            let formatComponents = parseFormatComponents(dateFormat)
            let inputComponents = Calendar.current.dateComponents(formatComponents, from: date)

            // 仅覆盖存在的组件
            for component in formatComponents {
                if component == .year { currentComponents.year = inputComponents.year }
                if component == .month { currentComponents.month = inputComponents.month }
                if component == .day { currentComponents.day = inputComponents.day }
                if component == .hour { currentComponents.hour = inputComponents.hour }
                if component == .minute { currentComponents.minute = inputComponents.minute }
                if component == .second { currentComponents.second = inputComponents.second }
            }
        }
        
        pickerVC.dateComponents = currentComponents
        pickerVC.onDateSelected = completion
        pickerVC.modalPresentationStyle = .popover
        pickerVC.popoverPresentationController?.delegate = pickerVC
        presentAsPopover(pickerVC, sourceView: sourceView)
    }
    private func parseFormatComponents(_ format: String) -> Set<Calendar.Component> {
        var components: Set<Calendar.Component> = []
        if format.contains("yyyy") { components.insert(.year) }
        if format.contains("MM") { components.insert(.month) }
        if format.contains("dd") { components.insert(.day) }
        if format.contains("HH") || format.contains("hh") { components.insert(.hour) }
        if format.contains("mm") { components.insert(.minute) }
        if format.contains("ss") { components.insert(.second) }
        return components
    }
    private func presentAsPopover(_ vc: UIViewController, sourceView: UIView) {
        
        guard let popover = vc.popoverPresentationController else { return }
        popover.sourceView = sourceView
        popover.sourceRect = sourceView.bounds
        popover.permittedArrowDirections = .up
        
        present(vc, animated: true)
    }
=======
class KLMTimePickerTestController: KLMBaseController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

>>>>>>> c9ff26f7439158038ece58549346ff469099cbd4
}
